package com.hyx.bookManager.adapter;

import com.hyx.bookManager.domain.common.Code;
import com.hyx.bookManager.domain.po.Permission;
import com.hyx.bookManager.domain.po.Role;
import com.hyx.bookManager.mapper.UserMapper;
import com.hyx.bookManager.utils.TokenUtil;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AdminInterceptor
 * @Description TODO
 * @Author 黄乙轩
 * @Date 2021/6/19 9:24
 * @Version 1.0
 **/

@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    public UserMapper userMapper;

    private TokenUtil tokenUtil = new TokenUtil();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token =request.getHeader("token");
        if(token==null){
            response.setStatus(Code.NOT_LOGIN.getCode());
            return false;
        }
        Map<String, Object> userMap = tokenUtil.validHS256(token);
        JSONObject data = (JSONObject)userMap.get("data");
        Long id = Long.valueOf((String)data.get("id"));
        Role userRole = userMapper.getUserRoleByAmmount(id);
        if(userRole.getRoleName().equals("超级管理员")){
            return true;
        }
        List<Permission> permissions = userMapper.getPermissionByRoleId(userRole.getRoleId());
        String servletPath = request.getServletPath();
        for(Permission permission:permissions){
            if(permission.getUrl().equals(servletPath)){
                return true;
            }
        }
        response.setStatus(Code.PERMISSIONERROR.getCode());
        return false;
    }
}
